package cn.dglydrpy.study.webserver.core;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * WebServer服务器
 */
public class WebServer {
	
	private ServerSocket server;
	
	private ExecutorService threadPool;

	/**
	 * 初始化服务器
	 */
	public WebServer() {
		System.out.println("########## 正在启动服务端... ##########");
		try {
			//Tomcat的默认服务端口是8080  本应用设置为8090
			server = new ServerSocket(8090);
			threadPool = Executors.newFixedThreadPool(100);
			System.out.println("########## 服务端启动完毕! ##########");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 服务器启动操作
	 */
	public void start() {
		try {
			while (true) {
				System.out.println("########## 等待客户端连接... ##########");
				Socket socket = server.accept();
				System.out.println("########## 有客户端连接了! ##########");
				// 启动线程处理该客户端操作
				ClientHandler handler = new ClientHandler(socket);
				threadPool.execute(handler);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
